﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;

namespace AltNetHispano.Vale.DataAnnotations
{
	public interface IDataAnnotationsInspector
	{
		IEnumerable<Func<T, string>> GetConstraints<T>();
	}

	public class DataAnnotationsInspector
		: IDataAnnotationsInspector
	{

		public class PropertyValidatorPair
		{
			public PropertyInfo Property { get; set; }
			public ValidationAttribute Validator { get; set; }
		}


		public IEnumerable<Func<T, string>> GetConstraints<T>()
		{
			var properties = typeof (T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

			var validators = from p in properties
							from v in p.GetCustomAttributes(true).OfType<ValidationAttribute>()
							select new PropertyValidatorPair {Property = p, Validator = v};


			return validators.Select(pair => 
				(Func<T, string>) (entity => Validate(pair.Validator, pair.Property.GetValue(entity, null))));
		}

		private static string Validate(ValidationAttribute validationAttribute, object propertyValue)
		{
			return validationAttribute.IsValid(propertyValue) 
			       	? string.Empty 
			       	: validationAttribute.ErrorMessage;
		}
	}
}
